﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Newtonsoft.Json;
using TdxHq.Common;
using TdxHq.Common.Provider;
using TdxHq.Connect;
using TdxHq.ErrorHandler;
using TdxHq.Invoker;

namespace TdxHq.Looper
{
    public class QueueLooper
    {
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(QueueLooper));
        
        public bool Stop = false;
        public Queue Queue = Queue.Synchronized(new Queue());
        public TdxConnection TdxConnection;

        public static QueueLooper Instance = new QueueLooper();

        private QueueLooper()
        {
        }

        public void Run()
        {
            while (!Stop)
            {
                if (Queue.Count == 0)
                {
                    Thread.Sleep(5);
                }
                else
                {
                    List<QuoteRt> dequeue = (List<QuoteRt>) Queue.Dequeue();                   
                    foreach (QuoteRt quoteRt in dequeue)
                    {
                        if(!SanpshootService.Snapshoot.ContainsKey(quoteRt.StkCode))
                        {
                            SaveHq(quoteRt);
                        }
                        
                        QuoteRt data = SanpshootService.Snapshoot.GetOrAdd(quoteRt.StkCode, quoteRt);

                        if (data.VolAll >= quoteRt.VolAll) continue;

                        SaveHq(quoteRt);
                        
                        SanpshootService.Snapshoot.AddOrUpdate(quoteRt.StkCode, quoteRt, (k, v) => quoteRt);
                        DateTime nowTime = DateTime.Now;
                        DateTime oldTime = SanpshootService.SnapshootUpdateTime.GetOrAdd(quoteRt.StkCode, nowTime);
                            
                        var delay = nowTime.Ticks - oldTime.Ticks;
                            
                        SanpshootService.SnapshootUpdateDelay.AddOrUpdate(quoteRt.StkCode, delay, (k, v) => delay);
                        SanpshootService.SnapshootUpdateTime.AddOrUpdate(quoteRt.StkCode, nowTime,
                            (k, v) => nowTime);
                    }
                }
            }
        }

        private void SaveHq(QuoteRt quoteRt)
        {
            try
            {
                SanpshootService.SnapshootQueue.Enqueue(quoteRt);
                //String content = JsonConvert.SerializeObject(quoteRt);
                //HqRedisProvider.SaveHq(quoteRt.StkCode,content);
                //HqRedisProvider.PushHq(quoteRt.StkCode,content);
            }
            catch (Exception e)
            {
                _log.Error("行情队列，redis存储错误");
                _log.Error(e);
                EmailSenter.SendEmail("redis存储错误", "行情队列，redis存储错误\n" + "exctption:" + e.Message);
            }
        }

        public void AddData(List<QuoteRt> quoteRts)
        {
            Queue.Enqueue(quoteRts);
        }
    }
}